package ranger.clips
{
    import com.lowke.animator.Animator;
    import com.lowke.animator.effect.AngleFramesFX;
    import com.lowke.animator.effect.VelocityFX;
    import com.lowke.animator.event.EffectEvent;
    
    import flash.geom.Point;

    public class PlayerShip extends Clip
    {
		private static const VELOCITY_MODIFIER:Number = 400;
		
        private var _velocityXEffect:VelocityFX;
        private var _velocityYEffect:VelocityFX;
        private var _angleFramesEffect:AngleFramesFX;
        private var _targetLocation:Point;
		private var _directionVector:Point;
        
        public function PlayerShip()
        {
            super("PlayerShip");
            
			x = RussellStarling.WIDTH/2;
			y = RussellStarling.HEIGHT/2;
			
            _targetLocation = new Point(x, y);
			_directionVector = new Point();
            
            // random x & y velocity
            var velocityX:Number = randomInt(60, 120)/1000*(randomInt(0, 1) ? 1 : -1);
            _velocityXEffect = new VelocityFX('x', velocityX, width/2, RussellStarling.WIDTH - width/2, false, Animator.TYPE_REVERSE);
            _anime.addEffect(_velocityXEffect);
            
            var velocityY:Number = randomInt(60, 120)/1000*(randomInt(0, 1) ? 1 : -1);
            _velocityYEffect = new VelocityFX('y', velocityY, height/2, RussellStarling.HEIGHT - height/2, false, Animator.TYPE_REVERSE);
            _anime.addEffect(_velocityYEffect);
            
            // always face the direction of movement
            _angleFramesEffect = new AngleFramesFX(0.6);
            _anime.addEffect(_angleFramesEffect);
			
			_angleFramesEffect.addEventListener(EffectEvent.EFFECT_UPDATED, update);
        }
		
		private function update(effect:EffectEvent):void
		{
			// aim the ship towards the crosshairs
			_directionVector.x = _targetLocation.x - x;
			_directionVector.y = _targetLocation.y - y;
			var angle:Number = Animator.vectorToAngle(_directionVector);
			_angleFramesEffect.targetAngle = angle;

			// and set its velocity
			_velocityXEffect.velocity = calculateVelocity(x, _targetLocation.x);
			_velocityYEffect.velocity = calculateVelocity(y, _targetLocation.y);
		}
		
		public function driveTo(point:Point):void
		{
			_targetLocation.x = point.x;
			_targetLocation.y = point.y;
		}
		
		private function calculateVelocity(value:Number, target:Number):Number
		{
			var direction:Number;
			var difference:Number = target - value;
			if (difference > 0) 
			{
				direction = +1;
			} 
			else if (difference < 0) 
			{
				direction = -1;
			} 
			else
			{
				direction = 0;
			}
			difference = Math.abs(difference);
			var velocity:Number = difference/VELOCITY_MODIFIER*direction;
			return velocity;
		}
    }
}